﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace OAZCSharpSdk.OAZ.Plugin.Extensions
{
    /// <summary>
    /// Json扩展方法
    /// </summary>
    public static class JsonExt
    {
        private static JavaScriptSerializer _js { get; set; }

        private static JavaScriptSerializer js
        {
            get
            {
                if (_js == null)
                {
                    _js = new JavaScriptSerializer();
                    _js.MaxJsonLength = int.MaxValue;
                }
                return _js;
            }
        }

        /// <summary>
        /// 将对象序列化成JSON
        /// </summary>
        /// <param name="obj">需要序列化的对象</param>
        /// <returns></returns>
        public static String JsonSerialize(this object obj)
        {
            return js.Serialize(obj);
        }

        /// <summary>
        /// 将JSON反序列化为实体
        /// </summary>
        /// <typeparam name="T">任意实体类</typeparam>
        /// <param name="json">json文本</param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(this String json)
        {
            return js.Deserialize<T>(json);
        }
    }
}
